// 系统设置类型定义

// 基础设置类型
export interface BasicSettings {
  // 系统名称设置
  systemName: string;
  systemLogo: string;
  welcomeMessage: string;
  
  // 时间设置
  timeZone: string;
  dateFormat: string;
  timeFormat: string;
  
  // 语言设置
  defaultLanguage: string;
  enabledLanguages: string[];
  
  // 分页设置
  defaultPageSize: number;
  maxPageSize: number;
  
  // 其他基础设置
  maintenanceMode: boolean;
  maintenanceMessage: string;
  sessionTimeout: number; // 分钟
}

// 安全设置类型
export interface SecuritySettings {
  // 密码策略
  passwordPolicy: {
    minLength: number;
    requireUppercase: boolean;
    requireLowercase: boolean;
    requireNumbers: boolean;
    requireSpecialChars: boolean;
    passwordExpiryDays: number;
    historyCount: number; // 记住的旧密码数量，防止重复使用
  };
  
  // 账户锁定
  accountLockout: {
    enabled: boolean;
    failedAttempts: number;
    lockoutDuration: number; // 分钟
  };
  
  // 多因素认证
  mfa: {
    enabled: boolean;
    enforcedForAdmin: boolean;
    methods: string[]; // 支持的MFA方法
  };
  
  // 登录安全
  loginSecurity: {
    maxSessionsPerUser: number;
    forceLogoutOnPasswordChange: boolean;
    disableLoginAfterInactivity: number; // 天数
  };
  
  // IP限制
  ipRestrictions: {
    enabled: boolean;
    allowedIPs: string[];
    blockedIPs: string[];
  };
}

// 通知设置类型
export interface NotificationSettings {
  // 邮件通知
  email: {
    enabled: boolean;
    smtpServer: string;
    smtpPort: number;
    smtpUsername: string;
    smtpPassword: string; // 实际存储时应加密
    useSSL: boolean;
    fromAddress: string;
    testEmail: string;
  };
  
  // 系统通知
  systemNotifications: {
    enabled: boolean;
    showInApp: boolean;
    emailAlerts: boolean;
    notificationExpiry: number; // 天
  };
  
  // 事件通知配置
  eventNotifications: {
    userLogin: boolean;
    userLogout: boolean;
    accountCreated: boolean;
    accountUpdated: boolean;
    accountDeleted: boolean;
    passwordChanged: boolean;
    securityViolation: boolean;
    systemError: boolean;
    dataImportExport: boolean;
  };
  
  // 提醒设置
  reminders: {
    attendanceDeadline: boolean;
    gradeSubmissionDeadline: boolean;
    upcomingExams: boolean;
    systemMaintenance: boolean;
    reminderLeadTime: number; // 提前多少小时提醒
  };
}

// 教务设置类型
export interface AcademicSettings {
  // 学期设置
  semesterSettings: {
    currentSemester: string;
    semesterStartDate: string;
    semesterEndDate: string;
    registrationStartDate: string;
    registrationEndDate: string;
  };
  
  // 考勤设置
  attendanceSettings: {
    defaultWorkingDays: string[]; // 默认为工作日的星期几
    checkInTime: string;
    checkOutTime: string;
    lateArrivalThreshold: number; // 分钟
    earlyDepartureThreshold: number; // 分钟
    absencesBeforeWarning: number;
  };
  
  // 成绩设置
  gradeSettings: {
    passingScore: number;
    gradeScale: {
      excellentMin: number;
      goodMin: number;
      fairMin: number;
      poorMin: number;
    };
    roundingMethod: string; // 'none', 'round', 'ceiling', 'floor'
    decimalPlaces: number;
  };
  
  // 课程设置
  courseSettings: {
    maxCoursesPerStudent: number;
    maxStudentsPerCourse: number;
    courseDurationDays: number;
    allowCoursePrerequisites: boolean;
  };
  
  // 报表设置
  reportSettings: {
    defaultReportFormat: string;
    includeStudentPhotos: boolean;
    showDetailedStatistics: boolean;
    exportFormats: string[];
  };
}

// 完整的系统设置类型
export interface SystemSettings {
  basic: BasicSettings;
  security: SecuritySettings;
  notification: NotificationSettings;
  academic: AcademicSettings;
  lastUpdated: string;
  updatedBy: string;
}

// 语言选项
export const languageOptions = [
  { value: 'zh-CN', label: '简体中文' },
  { value: 'en-US', label: 'English (US)' },
  { value: 'zh-TW', label: '繁體中文' },
];

// 日期格式选项
export const dateFormatOptions = [
  { value: 'YYYY-MM-DD', label: '2023-12-31' },
  { value: 'DD/MM/YYYY', label: '31/12/2023' },
  { value: 'MM/DD/YYYY', label: '12/31/2023' },
];

// 时间格式选项
export const timeFormatOptions = [
  { value: 'HH:mm:ss', label: '24小时制 (14:30:45)' },
  { value: 'hh:mm:ss A', label: '12小时制 (02:30:45 PM)' },
];

// 时区选项
export const timeZoneOptions = [
  { value: 'Asia/Shanghai', label: '中国标准时间 (UTC+8)' },
  { value: 'UTC', label: '协调世界时 (UTC)' },
  { value: 'America/New_York', label: '美国东部时间 (UTC-5/-4)' },
  { value: 'Europe/London', label: '格林威治标准时间 (UTC±0)' },
];

// 一周中的日期选项
export const weekDayOptions = [
  { value: 'monday', label: '周一' },
  { value: 'tuesday', label: '周二' },
  { value: 'wednesday', label: '周三' },
  { value: 'thursday', label: '周四' },
  { value: 'friday', label: '周五' },
  { value: 'saturday', label: '周六' },
  { value: 'sunday', label: '周日' },
];

// 舍入方法选项
export const roundingMethodOptions = [
  { value: 'none', label: '不舍入' },
  { value: 'round', label: '四舍五入' },
  { value: 'ceiling', label: '向上取整' },
  { value: 'floor', label: '向下取整' },
];

// 报表格式选项
export const reportFormatOptions = [
  { value: 'pdf', label: 'PDF' },
  { value: 'excel', label: 'Excel' },
  { value: 'csv', label: 'CSV' },
  { value: 'word', label: 'Word' },
];

// 导出格式选项
export const exportFormatOptions = [
  { value: 'excel', label: 'Excel (.xlsx)' },
  { value: 'csv', label: 'CSV (.csv)' },
  { value: 'pdf', label: 'PDF (.pdf)' },
];

// 生成默认设置
export const generateDefaultSettings = (): SystemSettings => ({
  basic: {
    systemName: '学生信息管理系统',
    systemLogo: '',
    welcomeMessage: '欢迎使用学生信息管理系统',
    timeZone: 'Asia/Shanghai',
    dateFormat: 'YYYY-MM-DD',
    timeFormat: 'HH:mm:ss',
    defaultLanguage: 'zh-CN',
    enabledLanguages: ['zh-CN', 'en-US'],
    defaultPageSize: 20,
    maxPageSize: 100,
    maintenanceMode: false,
    maintenanceMessage: '系统正在维护中，请稍后再试',
    sessionTimeout: 30,
  },
  security: {
    passwordPolicy: {
      minLength: 8,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: true,
      passwordExpiryDays: 90,
      historyCount: 5,
    },
    accountLockout: {
      enabled: true,
      failedAttempts: 5,
      lockoutDuration: 30,
    },
    mfa: {
      enabled: false,
      enforcedForAdmin: false,
      methods: ['email', 'sms'],
    },
    loginSecurity: {
      maxSessionsPerUser: 3,
      forceLogoutOnPasswordChange: true,
      disableLoginAfterInactivity: 90,
    },
    ipRestrictions: {
      enabled: false,
      allowedIPs: [],
      blockedIPs: [],
    },
  },
  notification: {
    email: {
      enabled: false,
      smtpServer: '',
      smtpPort: 587,
      smtpUsername: '',
      smtpPassword: '',
      useSSL: true,
      fromAddress: '',
      testEmail: '',
    },
    systemNotifications: {
      enabled: true,
      showInApp: true,
      emailAlerts: true,
      notificationExpiry: 7,
    },
    eventNotifications: {
      userLogin: true,
      userLogout: false,
      accountCreated: true,
      accountUpdated: true,
      accountDeleted: true,
      passwordChanged: true,
      securityViolation: true,
      systemError: true,
      dataImportExport: false,
    },
    reminders: {
      attendanceDeadline: true,
      gradeSubmissionDeadline: true,
      upcomingExams: true,
      systemMaintenance: true,
      reminderLeadTime: 24,
    },
  },
  academic: {
    semesterSettings: {
      currentSemester: '2024春季学期',
      semesterStartDate: new Date(new Date().getFullYear(), 1, 1).toISOString().split('T')[0],
      semesterEndDate: new Date(new Date().getFullYear(), 5, 30).toISOString().split('T')[0],
      registrationStartDate: new Date(new Date().getFullYear(), 0, 15).toISOString().split('T')[0],
      registrationEndDate: new Date(new Date().getFullYear(), 1, 10).toISOString().split('T')[0],
    },
    attendanceSettings: {
      defaultWorkingDays: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
      checkInTime: '08:30',
      checkOutTime: '17:30',
      lateArrivalThreshold: 15,
      earlyDepartureThreshold: 15,
      absencesBeforeWarning: 3,
    },
    gradeSettings: {
      passingScore: 60,
      gradeScale: {
        excellentMin: 90,
        goodMin: 80,
        fairMin: 70,
        poorMin: 60,
      },
      roundingMethod: 'round',
      decimalPlaces: 1,
    },
    courseSettings: {
      maxCoursesPerStudent: 8,
      maxStudentsPerCourse: 40,
      courseDurationDays: 180,
      allowCoursePrerequisites: true,
    },
    reportSettings: {
      defaultReportFormat: 'pdf',
      includeStudentPhotos: true,
      showDetailedStatistics: true,
      exportFormats: ['excel', 'pdf'],
    },
  },
  lastUpdated: new Date().toISOString(),
  updatedBy: '系统管理员',
});

// 验证设置数据
export const validateSettings = (settings: Partial<SystemSettings>): { isValid: boolean; errors: string[] } => {
  const errors: string[] = [];
  
  // 验证基础设置
  if (settings.basic) {
    if (!settings.basic.systemName || settings.basic.systemName.trim() === '') {
      errors.push('系统名称不能为空');
    }
    if (settings.basic.defaultPageSize < 5 || settings.basic.defaultPageSize > 100) {
      errors.push('默认页面大小必须在5到100之间');
    }
    if (settings.basic.maxPageSize < settings.basic.defaultPageSize) {
      errors.push('最大页面大小不能小于默认页面大小');
    }
    if (settings.basic.sessionTimeout < 5 || settings.basic.sessionTimeout > 120) {
      errors.push('会话超时时间必须在5到120分钟之间');
    }
  }
  
  // 验证安全设置
  if (settings.security) {
    if (settings.security.passwordPolicy) {
      if (settings.security.passwordPolicy.minLength < 6) {
        errors.push('密码最小长度不能小于6个字符');
      }
      if (settings.security.passwordPolicy.passwordExpiryDays < 1) {
        errors.push('密码过期天数不能小于1天');
      }
    }
    if (settings.security.accountLockout) {
      if (settings.security.accountLockout.failedAttempts < 3) {
        errors.push('账户锁定失败尝试次数不能小于3次');
      }
    }
  }
  
  // 验证通知设置
  if (settings.notification?.email?.enabled) {
    if (!settings.notification.email.smtpServer || !settings.notification.email.fromAddress) {
      errors.push('启用邮件通知时，必须填写SMTP服务器和发件人地址');
    }
    if (settings.notification.email.smtpPort < 1 || settings.notification.email.smtpPort > 65535) {
      errors.push('SMTP端口号无效');
    }
  }
  
  // 验证教务设置
  if (settings.academic) {
    if (settings.academic.gradeSettings) {
      if (settings.academic.gradeSettings.passingScore < 0 || settings.academic.gradeSettings.passingScore > 100) {
        errors.push('及格分数必须在0到100之间');
      }
    }
  }
  
  return {
    isValid: errors.length === 0,
    errors,
  };
};